// 用户登录云函数
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { code } = event
  
  try {
    console.log('用户登录:', {
      openid: wxContext.OPENID,
      appid: wxContext.APPID,
      unionid: wxContext.UNIONID,
      code: code
    })

    // 检查用户是否已存在
    const userResult = await db.collection('users')
      .where({
        openid: wxContext.OPENID
      })
      .get()

    let userData = {
      openid: wxContext.OPENID,
      appid: wxContext.APPID,
      unionid: wxContext.UNIONID,
      last_login: new Date()
    }

    if (userResult.data.length === 0) {
      // 新用户，创建用户记录，设置默认信息
      userData.created_at = new Date()
      userData.is_new_user = true
      userData.nickName = '起个喜欢的名字吧~'
      userData.avatarUrl = '/images/img1.jpg'
      userData.profile_completed = false // 标记用户信息未完善
      
      const addResult = await db.collection('users').add({
        data: userData
      })
      
      userData._id = addResult._id
      console.log('新用户创建成功:', userData)
    } else {
      // 老用户，更新最后登录时间
      const existingUser = userResult.data[0]
      
      await db.collection('users')
        .doc(existingUser._id)
        .update({
          data: {
            last_login: new Date()
          }
        })
      
      userData = {
        ...existingUser,
        last_login: new Date(),
        is_new_user: false
      }
      
      console.log('老用户登录成功:', userData)
    }

    return {
      status: 'success',
      data: userData
    }

  } catch (error) {
    console.error('用户登录失败:', error)
    return {
      status: 'error',
      message: '用户登录失败',
      error: error.message
    }
  }
}
